package com.itcast.plane.modoule.picture.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.plane.common.ConsHint;
import com.itcast.plane.modoule.picture.domain.Picture;
import com.itcast.plane.modoule.picture.mapper.PictureMapper;
import com.itcast.plane.util.JsonResult;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@Service
public class PictureService extends ServiceImpl<PictureMapper, Picture> {

    @Resource
    private PictureMapper pictureMapper;

    public void fileDownload(HttpServletResponse response, int id) {
        Picture picture = pictureMapper.selectById(id);
        // 读到流中
        String name = picture.getName();
        String address = ConsHint.path + "/" + name;
        File file = null;
        try {
            file = new File(address);
        } catch (Exception e) {
            e.printStackTrace();
        }

        InputStream inputStream = null;

        ServletOutputStream outputStream;

        if (!file.exists()) {

            file = null;
            ClassPathResource resource = new ClassPathResource("/static/images/photogone.png");
            try {
                file = resource.getFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            inputStream = new FileInputStream(file);
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = new File(ConsHint.path).getName();
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while (true) {
                if (!((len = inputStream.read(b)) > 0)) {
                    break;
                }
                outputStream.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public JsonResult upload(MultipartFile mfile) {
        //存库
        String oldName = mfile.getName();
        int begin = oldName.indexOf(".");
        int last = oldName.length();
        String type = oldName.substring(begin, last);
        String naming = UUID.randomUUID().toString();
        String name = naming + type;
        String address = ConsHint.path + "/" + name;
        Picture picture = new Picture();
        picture.setName(name);
        picture.setAddress(address);
        pictureMapper.insert(picture);
        //保存图片到指定位置
        File file = new File(ConsHint.path);
        if (!file.exists()) {
            file.mkdirs();
        }
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream output = null;
        InputStream inputStream = null;
        try {
            output = new FileOutputStream(address);
            inputStream = mfile.getInputStream();
            while ((index = inputStream.read(bytes)) != -1) {
                output.write(bytes, 0, index);
                output.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //返回存储的id
        LambdaQueryWrapper<Picture> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Picture picture1 = pictureMapper.selectOne(lambdaQueryWrapper.eq(Picture::getName,name));
        return new JsonResult(true,ConsHint.UPLOAD_SUCCESS,picture1.getId());

    }
}
